define(['app', 'csv', 'handsontable', 'handsontable-zh-CN'], function(app, CSV, Handsontable) {
    app.controller('CsvDatatableController', function($scope, $compile, $timeout, xUtil, xDialog, toastr) {
        var self = this;

        var datatable = null;
        var filename = '新建文档.csv';

        self.init = function() {
            xUtil.clipboard.copy('#copy', function() {
                return encodeCsvData();
            });

            $timeout(function() {
                datatable = new Handsontable($('#datatable')[0], {
                    language: 'zh-CN',
                    type: 'text',
                    data: [['表头'], ['数据...']],
                    width: '100%',
                    height: '100%',
                    colWidths: 100,
                    colHeaders: true,
                    rowHeaders: true,
                    wordWrap: false,
                    autoColumnSize: true,
                    minSpareRows: 1,
                    columnSorting: true,
                    dropdownMenu: true,
                    contextMenu: true,
                    trimRows: true,
                    trimWhitespace: true,
                    manualColumnFreeze: true,
                    manualColumnResize: true,
                    manualRowResize: true,
                    manualColumnMove: true,
                    manualRowMove: true,
                    mergeCells: false,
                    filters: true,
                    search: true,
                    licenseKey: 'non-commercial-and-evaluation'
                });

                var queryResult = [], lastSelectIndex = -1;
                $('#query').unbind().bind('keyup', function(e) {
                    if (e.keyCode == 13) {
                        if (queryResult.length > 0) {
                            if (++lastSelectIndex >= queryResult.length) {
                                lastSelectIndex = 0;
                            }
                            var currentResult = queryResult[lastSelectIndex];
                            datatable.selectCell(currentResult.row, currentResult.col, currentResult.row,
                                    currentResult.col, true, false);
                            this.focus();
                        } else {
                            if (this.value) {
                                toastr.warning('查找不到【' + this.value + '】！');
                            } else {
                                toastr.warning('查找内容不可以为空！');
                            }
                        }
                    } else {
                        lastSelectIndex = -1;
                        queryResult = datatable.getPlugin('search').query(this.value);
                        datatable.render();
                    }
                });
            });
        }

        self.callback = function(height, width, refresh) {
            $('.x-datatable .x-view-scope').css('height', height + 'px');
            $timeout(function() {
                datatable.refreshDimensions();
            });
            // Toolbar
            if (refresh) {
                $('.navbar-form').append($compile($('#opt-toolbar').html())($scope));
            }
        }

        function loadCsvData(data) {
            var dataRows = [];
            if (data) {
                var dataset = CSV.parse(data, { cast: false });
                if (_.isEmpty(dataset)) {
                    dataRows.push(['']);
                } else {
                    _.forEach(dataset, function(row) {
                        dataRows.push(_.map(row, function(cell) {
                            return cell == '' ? null : cell;
                        }));
                    });
                }
            } else {
                dataRows.push(['']);
            }
            datatable.clear();
            datatable.loadData(dataRows);
            datatable.deselectCell();
        }

        function encodeCsvData() {
            if (datatable) {
                var dataset = [];
                var dataRows = datatable.getData();
                _.forEach(dataRows, function(row, i) {
                    if (i == dataRows.length - 1) {
                        if (datatable.isEmptyRow(i)) {
                            return;
                        }
                    }
                    dataset.push(_.map(row, function(cell) {
                        return cell ? cell : '';
                    }));
                });
                return CSV.encode(dataset, { cast: false, lineDelimiter: '\n' });
            }
            return '';
        }

        self.open = function(file) {
            if (file != null) {
                if (/\.csv$/i.test(file.name)) {
                    filename = file.name;
                    // open file
                    xUtil.file.open(file).then(function(response) {
                        loadCsvData(response.data);
                    });
                } else {
                    xDialog.alert('提示信息', '您打开的不是CSV文件！');
                }
            }
        }

        self.saveAs = function() {
            xUtil.file.save(filename, encodeCsvData());
        }

        self.clear = function() {
            filename = '新建文档.csv';
            datatable.clear();
            datatable.loadData([['']]);
            datatable.deselectCell();
        }
    });
});
